package com.changgou.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/sku_search")
public class SearchController {


    @Autowired
    private SearchService searchService;


    @GetMapping("/list")
    public String list(@RequestParam  Map<String,String> paramMap , Model model){
        //特殊符号处理;
        this.handlerSearchMap(paramMap);
        Map resultMap = searchService.search(paramMap);

        //传参
        model.addAttribute("resultMap" ,resultMap );       //返回的数据
        model.addAttribute("searchMap",paramMap);        //查询的数据

        //url处理
        StringBuilder url = new StringBuilder("/sku_search/list");
        if(paramMap != null && paramMap.size()> 0){
            //是否查询条件
            url.append("?");
            for (String paramKey : paramMap.keySet()) {
                if(!"sortRule".equals(paramKey) && !"sortField".equals(paramKey) && !"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(paramMap.get(paramKey)).append("&");
                }
            };
            String s = url.toString();
            String substring = s.substring(0, s.length() - 1);
            model.addAttribute("url",substring);
        }else {
            model.addAttribute("url",url);
        }

        //分页处理
        //1.总记录数
        //2.当前页
        //3.每页显示多少条
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(String.valueOf(resultMap.get("total"))),
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),
                Page.pageSize
        );
        model.addAttribute("page",page);

        return "search";
    }


    /**
     * 全文检索
     * @param paramMap
     * @return
     */
    @GetMapping
    @ResponseBody
    public Map search(@RequestParam  Map<String,String> paramMap ){
        //特殊符号处理;
        this.handlerSearchMap(paramMap);
        Map resultMap = searchService.search(paramMap);
        return resultMap;
    }

    //对带有特殊符号的参数进行处理
    public void handlerSearchMap(Map<String , String > paramMap){

        if(paramMap != null){
            Set<Map.Entry<String, String>> entries = paramMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if(entry.getKey().startsWith("spec_")){
                    paramMap.put(entry.getKey(), entry.getValue().replace("+","%2B"));
                }
            }
        }
    }
}
